package TeleRobot;
import java.awt.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;
public class RoboticsApp
{
    static Robot2 robo;
    static MyFrame mainFrame;
    static boolean server_mode = false;
    private static Socket clientSocket = null; //For client only
    private static PrintWriter out = null; //For client only
    private static Timer timer; //For client only
    
    static class DelayedSend extends TimerTask
    {
        String tosend;
        DelayedSend(String tosend)
        {
            this.tosend = tosend;
        }
        
        public void run()
        {
            out.println(tosend);
        }
    }
    
    public static void main(String[] args) 
    {
        System.out.println("Robotics Program Started.");
        
        Object[] options = {"Server","Client"};
        int n = JOptionPane.showOptionDialog(mainFrame,
        "Select mode for this instance:",
        "Mode Select",
        JOptionPane.YES_NO_OPTION,
        JOptionPane.QUESTION_MESSAGE,
        null,     //do not use a custom Icon
        options,  //the titles of buttons
        options[0]); //default button title
        
        if(n == JOptionPane.YES_OPTION)
            server_mode = true;
        else
            server_mode = false;
        
        System.out.println("server_mode:" + server_mode);
        
        
                    
        
        robo = new Robot2();
        mainFrame = new MyFrame();
        
        //MyFrame mainFrame = new MyFrame();
        mainFrame.setSize(970, 700);
        mainFrame.setVisible(true);
        
        if(server_mode)
        {
            runServer();
        }
        else
        {
            clientInitialize();
        }
        
    }
    
    public static void runServer()
    {
        //Print local ip address
        try
        {
            InetAddress addr = InetAddress.getLocalHost();
            String hostname = addr.getHostName();
            System.out.println(addr.getHostAddress());
            //System.out.println(hostname);
        }catch(UnknownHostException e)
        {
            System.err.println("Failed to get local IP");
            System.exit(1);
        }
        
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(4444);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 4444.");
            System.exit(1);
        }
        
        Socket clientSocket = null;
        try {
            clientSocket = serverSocket.accept();
        } catch (IOException e) {
            System.err.println("Accept failed.");
            System.exit(1);
        }
        try{
            //PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        
            String inputLine;

            /*
             * Message: theta1,theta2,theta3,paint_status,delay_status
             * 
             * paint_status: on,off
             * delay_status: on,off
             * thetas: double
             */

            while ((inputLine = in.readLine()) != null)
            {
                StringTokenizer st = new StringTokenizer(inputLine,",");
                double t1 = Double.parseDouble(st.nextToken());
                double t2 = Double.parseDouble(st.nextToken());
                double t3 = Double.parseDouble(st.nextToken());
                if(st.nextToken().equals("on"))
                {
                    robo.setPaint(true);
                }
                else
                {
                    robo.setPaint(false);
                }
                if(st.nextToken().equals("on"))
                {
                    robo.setDelay(true);
                }
                else
                {
                    robo.setDelay(false);
                }
                robo.redraw(mainFrame.getGraphics(), t1, t2, t3);
                mainFrame.repaint();
            }

            in.close();
            clientSocket.close();
            serverSocket.close();
        
        } catch(IOException e)
            {
                System.err.println("Failed to initialize IO on socket");
                System.exit(1);
            }
    }
    
    public static void clientInitialize()
    {
        //Dialog to get ip
        String ipAddress = (String)JOptionPane.showInputDialog(
                      mainFrame,
                      "Type in the server IP address:",
                      "Server IP Address",
                      JOptionPane.PLAIN_MESSAGE);
        
        
        //Initialize socket
        try {
            clientSocket = new Socket(ipAddress, 4444);
            out = new PrintWriter(clientSocket.getOutputStream(), true);
        } catch (UnknownHostException e) {
            System.err.println("Failed to find host");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection");
            System.exit(1);
        }
        
        //Initialize Timer
        timer = new Timer();
    }
    
    public static void clientSend()
    {
        if(!server_mode)
        {
            if(robo.getDelay())
            {
                timer.schedule(new DelayedSend(robo.toString()), 2000);
            }
            else
            {
                String tosend = robo.toString();
                out.println(tosend);
            }
        }
    }
}
